/**
 * XRK-Core 插件主入口
 * 整合原神相关功能和运行时扩展
 */

import fs from 'fs';
import path from 'path';
import chalk from 'chalk';

// 导入运行时和扩展
import Runtime from '../../lib/plugins/runtime.js';
import GenshinExtension, { createCompatibilityProxy } from './apps/Genshin.js';

// ========== 应用动态加载 ==========
const appsDir = './plugins/XRK-Core/apps';
let apps = {};

/**
 * 动态加载所有应用模块
 */
async function loadApps() {
  try {
    const files = fs
      .readdirSync(appsDir)
      .filter((file) => file.endsWith('.js') && file !== 'Genshin.js');

    if (files.length === 0) {
      logger.warn(chalk.yellow('[XRK-Core] 未找到任何应用模块'));
      return {};
    }

    // 动态导入所有模块
    const importPromises = files.map((file) => import(`./apps/${file}`));
    const results = await Promise.allSettled(importPromises);

    // 处理导入结果
    const loadedApps = {};
    const failedApps = [];
    
    for (let i = 0; i < files.length; i++) {
      const fileName = files[i].replace('.js', '');
      const result = results[i];

      if (result.status === 'fulfilled') {
        const moduleExports = result.value;
        const exportKeys = Object.keys(moduleExports);
        
        if (exportKeys.length > 0) {
          loadedApps[fileName] = moduleExports[exportKeys[0]];
          logger.info(chalk.green(`[XRK-Core] ✓ 加载应用: ${fileName}`));
        } else {
          failedApps.push(fileName);
          logger.warn(chalk.yellow(`[XRK-Core] ⚠ 应用无导出: ${fileName}`));
        }
      } else {
        failedApps.push(fileName);
        logger.error(chalk.red(`[XRK-Core] ✗ 加载失败: ${fileName}`));
        logger.error(result.reason);
      }
    }

    // 输出加载统计
    if (Object.keys(loadedApps).length > 0) {
      logger.info(chalk.cyan(`[XRK-Core] 成功加载 ${Object.keys(loadedApps).length}/${files.length} 个应用`));
    }
    
    if (failedApps.length > 0) {
      logger.warn(chalk.yellow(`[XRK-Core] 失败的应用: ${failedApps.join(', ')}`));
    }

    return loadedApps;
  } catch (error) {
    logger.error(chalk.red('[XRK-Core] 应用加载过程出错:'), error);
    return {};
  }
}

/**
 * 生成miao-plugin导入配置
 */
function createMiaoConfig() {
  try {
    const configDir = './data/importsJson';
    const configFile = path.join(configDir, 'miao-plugin.json');
    
    // 检查miao-plugin是否存在
    if (!fs.existsSync('./plugins/miao-plugin')) {
      logger.debug('[XRK-Core] miao-plugin 未安装，跳过配置生成');
      return false;
    }
    
    // 创建目录
    if (!fs.existsSync(configDir)) {
      fs.mkdirSync(configDir, { recursive: true });
    }
    
    // 写入配置
    const config = {
      imports: {
        "#miao": "./plugins/miao-plugin/components/index.js",
        "#miao.models": "./plugins/miao-plugin/models/index.js"
      }
    };
    
    fs.writeFileSync(configFile, JSON.stringify(config, null, 2));
    logger.info(chalk.green('[XRK-Core] ✓ miao-plugin 配置已生成'));
    return true;
  } catch (error) {
    logger.error(chalk.red('[XRK-Core] miao-plugin 配置生成失败:'), error);
    return false;
  }
}

/**
 * 初始化运行时扩展
 */
function initRuntimeExtension() {
  try {
    if (!Runtime.registerExtension) {
      logger.warn(chalk.yellow('[XRK-Core] 当前版本的Runtime不支持扩展机制'));
      return false;
    }

    // 注册游戏扩展
    Runtime.registerExtension('game', GenshinExtension);
    logger.info(chalk.green('[XRK-Core] ✓ 游戏扩展已注册'));
    
    // 包装原始的init方法
    const originalInit = Runtime.init;
    Runtime.init = async function(e) {
      try {
        // 调用原始的init方法
        const runtime = await originalInit.call(this, e);
        
        // 如果有game扩展，创建兼容性代理
        if (runtime && runtime.getExtension && runtime.getExtension('game')) {
          e.runtime = createCompatibilityProxy(runtime);
        } else {
          e.runtime = runtime;
        }
        
        return e.runtime;
      } catch (error) {
        logger.error(chalk.red('[XRK-Core] Runtime初始化失败:'), error);
        throw error;
      }
    };
    
    logger.info(chalk.green('[XRK-Core] ✓ Runtime 扩展初始化完成'));
    return true;
  } catch (error) {
    logger.error(chalk.red('[XRK-Core] Runtime扩展初始化失败:'), error);
    return false;
  }
}

/**
 * 插件初始化函数
 */
async function init() {
  logger.info(chalk.cyan('========================================'));
  logger.info(chalk.cyan('[XRK-Core] Yunzai适配器插件初始化开始...'));
  logger.info(chalk.cyan('========================================'));
  
  // 生成miao配置
  const miaoConfigured = createMiaoConfig();
  
  // 初始化运行时扩展
  const extensionInitialized = initRuntimeExtension();
  
  // 动态加载应用模块
  apps = await loadApps();
  const loadedApps = Object.keys(apps);
  
  // 输出初始化结果
  logger.info(chalk.cyan('========================================'));
  logger.info(chalk.green('[XRK-Core] 初始化完成!'));
  logger.info(chalk.cyan(`- Miao配置: ${miaoConfigured ? '✓' : '✗'}`));
  logger.info(chalk.cyan(`- 运行时扩展: ${extensionInitialized ? '✓' : '✗'}`));
  logger.info(chalk.cyan(`- 加载应用数: ${loadedApps.length}`));
  if (loadedApps.length > 0) {
    logger.info(chalk.cyan(`  应用列表: ${loadedApps.join(', ')}`));
  }
  logger.info(chalk.cyan('========================================'));
  
  return {
    apps,
    extensionInitialized,
    miaoConfigured,
    loadedApps
  };
}

// 自动初始化（可通过环境变量禁用）
if (process.env.AUTO_INIT !== 'false') {
  await init();
}

// 导出
export { apps, init };

// 默认导出
export default {
  apps,
  init
};